﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Contracts;
using System.ComponentModel.Composition;

namespace WpfAppHost
{
    /// <summary>
    /// Interaction logic for AddinsUserControl.xaml
    /// </summary>
    public partial class AddinsUserControl : UserControl
    {
        private IWpfHost _host;
        Microsoft.Win32.OpenFileDialog dlg;

        public AddinsUserControl()
        {
            InitializeComponent();

            dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DereferenceLinks = true;
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;
            dlg.DefaultExt = "util";
            dlg.Filter = "Utility Runner Addin (*.util)|*.util";
            dlg.FileOk += new System.ComponentModel.CancelEventHandler(dlg_FileOk);
        }

        public IWpfHost ServiceHost
        {
            get
            {
                return _host;
            }
            set
            {
                _host = value;
                listBoxInstalled.ItemsSource = _host.AddinManager.Addins.Where(a => !(a is IWpfServiceAdmin));
                //AddinManager.Current.AddinLoaded += new EventHandler(Instance_AddinLoaded);
            }
        }

        void Instance_AddinLoaded(object sender, EventArgs e)
        {
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            dlg.ShowDialog();
        }

        void dlg_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _host.AddinManager.InstallAddin(dlg.FileName);
            MessageBox.Show("You have installed a new addin.  You must restart MEF Utility Runner to begin using it.");
        }

        private void DisableButton_Click(object sender, RoutedEventArgs e)
        {
            //IWpfService addin = ((System.Windows.Controls.Button)e.OriginalSource).DataContext as IWpfService;
            //_host.AddinManager.DisableAddin(addin);
        }

        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            IWpfService addin = ((System.Windows.Controls.Button)e.OriginalSource).DataContext as IWpfService;
            _host.AddinManager.UninstallAddin(addin);
            MessageBox.Show("You have removed this addin.  You must restart MEF Utility Runner for changes to take effect.");
        }
    }
}
